package com.dezheyun.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

/**
 * 资源微服务，这里只是模拟，记录一下操作
 */
@Configuration
@EnableResourceServer //表示是资源服务，解自动增加了一个类型为OAuth2AuthenticationProcessingFilter 的过滤链
public class MyResourceConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        //资源名称
        resources.resourceId("dzRe")
                .tokenServices(this.tokenServices())
                .stateless(true);  //无状态
    }

    /**
     * 配置资源token信息
     */
    public ResourceServerTokenServices tokenServices() {
        RemoteTokenServices tokenServices = new RemoteTokenServices();
        //检查
        tokenServices.setCheckTokenEndpointUrl("http://127.0.0.1:8001/oauth/check_token");
        //客户端的名称和密码
        tokenServices.setClientId("dz");
        tokenServices.setClientSecret("123");
        return tokenServices;
    }

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/**").access("#oauth2.hasAnyScope('all')")
                //其他请求都放过
                .anyRequest().permitAll()
                .and().csrf().disable()
                //不需要session管理
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
